package io.gitee.zhucan123.core.infrastructure.dataconversion;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * @author: zhuCan
 * @date: 18:05
 * @description: 枚举反序列化
 */
@Data
public class EnumDeserialize extends JsonDeserializer<Enum> implements ContextualDeserializer {

  /**
   * 枚举类的class
   */
  private Class clazz;

  /**
   * 执行反序列化
   *
   * @param p
   * @param context
   * @return
   * @throws IOException
   */
  @Override
  public Enum deserialize(JsonParser p, DeserializationContext context) throws IOException {

    if (!StringUtils.isEmpty(p.getText()) && IntegerEnum.class.isAssignableFrom(clazz) && isInteger(p.getText())) {
      return (Enum) IntegerEnum.valueOf(clazz, Integer.valueOf(p.getText()));
    }

    return null;
  }

  /**
   * 获取 需要转的枚举的 class
   *
   * @param context
   * @param property
   * @return
   */
  @Override
  public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
    Class rawCls = context.getContextualType().getRawClass();
    EnumDeserialize clone = new EnumDeserialize();
    clone.setClazz(rawCls);
    return clone;

  }

  /**
   * 判断是否为整数
   *
   * @param str 传入的字符串
   * @return 是整数返回true, 否则返回false
   */
  public static boolean isInteger(String str) {
    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
    return pattern.matcher(str).matches();
  }
}
